package com.fdd.furns.dao.impl;

import com.fdd.furns.dao.BasicDAO;
import com.fdd.furns.dao.FurnDAO;
import com.fdd.furns.entity.Furn;

import java.util.Collections;
import java.util.List;

public class FurnDAOImpl extends BasicDAO implements FurnDAO {

    @Override
    public List<Furn> queryFurns() {
        String sql = "select `id`,`name`,maker,price,sales,stock,img_path imgPath from furn";
        return queryMulti(sql, Furn.class);
    }

    @Override
    public int add(Furn furn) {
        String sql = "insert into furn(`id`,`name`,maker,price,sales,stock,img_path) values(null,?,?,?,?,?,?)";
        return update(sql, furn.getName(), furn.getMaker(), furn.getPrice(), furn.getSales(), furn.getStock(), furn.getImgPath());
    }

    @Override
    public int deleteFurnById(int id) {
        String sql = "delete from furn where id = ?";
        return update(sql, id);
    }

    @Override
    public Furn queryFurnById(int id) {
        String sql = "select `id`,`name`,maker,price,sales,stock,img_path imgPath from furn where id = ?";
        return (Furn) querySingle(sql, Furn.class, id);
    }

    //取出当前页的数据
    @Override
    public List<Furn> getPageItems(int begin, int pageSize) {
        String sql = "select `id`,`name`,maker,price,sales,stock,img_path imgPath from furn limit ?,?";
        return queryMulti(sql, Furn.class, begin, pageSize);
    }


    //在原有的furn对象修改，因此id不需要传，直接从传过来的对象中取就好
    @Override
    public int updateFurn(Furn furn) {
        String sql = "UPDATE `furn` SET `name` = ?, `maker` = ?, `price` = ?, `sales` = ?, `stock` = ?, `img_path` = ? WHERE `id` = ?; ";
        return update(sql,furn.getName(), furn.getMaker(), furn.getPrice(), furn.getSales(), furn.getStock(), furn.getImgPath(), furn.getId());
    }

    //从数据库获取总记录数
    @Override
    public int getTotalRow() {
        String sql = "select count(*) from furn";
        return ((Number) queryScalar(sql)).intValue();
    }

    //根据家具名模糊查询
    @Override
    public int getTotalRowByName(String name) {
        String sql = "select count(*) from `furn` where `name` like ?";

        return ((Number)queryScalar(sql, "%" + name + "%")).intValue();
    }

    @Override
    public List<Furn> getPageItemsByName(int begin, int pageSize, String name) {
        String sql = "select `id`,`name`,maker,price,sales,stock,img_path imgPath from furn where `name` like ? limit ?,?";
        return queryMulti(sql, Furn.class, "%" + name + "%",begin, pageSize);

    }


}
